<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>高级数独游戏</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  
  <!-- Tailwind 配置 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#3B82F6',
            secondary: '#10B981',
            accent: '#8B5CF6',
            neutral: '#1F2937',
            'board-bg': '#F3F4F6',
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>
  
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .cell-border {
        @apply border border-gray-300;
      }
      .thick-right {
        @apply border-r-2 border-r-gray-600;
      }
      .thick-bottom {
        @apply border-b-2 border-b-gray-600;
      }
      .cell-highlight {
        @apply bg-blue-100 transition-colors duration-200;
      }
      .number-selected {
        @apply bg-primary text-white transition-all duration-200;
      }
      .number-candidate {
        @apply text-secondary font-medium;
      }
      .number-conflict {
        @apply text-red-500 font-bold;
      }
      .note-cell {
        @apply text-xs text-gray-500 grid grid-cols-3 grid-rows-3 gap-0.5;
      }
      .note-value {
        @apply flex items-center justify-center h-4 w-4;
      }
      .note-value-highlight {
        @apply bg-blue-100 rounded-full;
      }
    }
  </style>
</head>
<body class="bg-gradient-to-br from-gray-50 to-gray-100 min-h-screen font-sans text-neutral">
  <div class="container mx-auto px-4 py-8 max-w-4xl">
    <!-- 标题区域 -->
    <header class="text-center mb-8">
      <h1 class="text-[clamp(2rem,5vw,3rem)] font-bold text-primary mb-2">数独大师</h1>
      <p class="text-gray-600 text-lg">挑战你的逻辑思维能力</p>
    </header>
    
    <!-- 游戏控制面板 -->
    <div class="bg-white rounded-xl shadow-lg p-6 mb-8 transform transition-all duration-300 hover:shadow-xl">
      <div class="flex flex-col md:flex-row justify-between items-center gap-4">
        <!-- 计时器 -->
        <div class="flex items-center gap-3 bg-gray-50 p-3 rounded-lg shadow-sm">
          <i class="fa fa-clock-o text-primary text-xl"></i>
          <div>
            <p class="text-sm text-gray-500">用时</p>
            <p id="timer" class="text-2xl font-mono font-bold">00:00</p>
          </div>
        </div>
        
        <!-- 难度选择 -->
        <div class="flex flex-col items-start">
          <label for="difficulty" class="text-sm text-gray-500 mb-1">难度</label>
          <select id="difficulty" class="bg-gray-50 border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary/50">
            <option value="easy">简单</option>
            <option value="medium" selected>中等</option>
            <option value="hard">困难</option>
            <option value="expert">专家</option>
          </select>
        </div>
        
        <!-- 操作按钮 -->
        <div class="flex gap-3">
          <button id="new-game" class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg shadow transition-all duration-200 flex items-center gap-2">
            <i class="fa fa-refresh"></i>
            <span>新游戏</span>
          </button>
          <button id="hint" class="bg-secondary hover:bg-secondary/90 text-white px-4 py-2 rounded-lg shadow transition-all duration-200 flex items-center gap-2">
            <i class="fa fa-lightbulb-o"></i>
            <span>提示</span>
          </button>
          <button id="toggle-notes" class="bg-accent hover:bg-accent/90 text-white px-4 py-2 rounded-lg shadow transition-all duration-200 flex items-center gap-2">
            <i class="fa fa-pencil"></i>
            <span>笔记</span>
          </button>
        </div>
      </div>
    </div>
    
    <!-- 数独游戏区域 -->
    <div class="flex flex-col items-center">
      <div id="sudoku-board" class="grid grid-cols-9 grid-rows-9 bg-board-bg rounded-xl shadow-lg p-1 transition-all duration-300">
        <!-- 数独单元格将通过JS动态生成 -->
      </div>
      
      <!-- 数字选择器 -->
      <div id="number-pad" class="grid grid-cols-9 gap-2 mt-6 w-full max-w-md">
        <!-- 数字1-9和清除按钮 -->
        <button class="number-btn bg-white hover:bg-gray-100 border border-gray-200 rounded-lg py-3 text-xl font-bold transition-all duration-200 shadow-sm hover:shadow">1</button>
        <button class="number-btn bg-white hover:bg-gray-100 border border-gray-200 rounded-lg py-3 text-xl font-bold transition-all duration-200 shadow-sm hover:shadow">2</button>
        <button class="number-btn bg-white hover:bg-gray-100 border border-gray-200 rounded-lg py-3 text-xl font-bold transition-all duration-200 shadow-sm hover:shadow">3</button>
        <button class="number-btn bg-white hover:bg-gray-100 border border-gray-200 rounded-lg py-3 text-xl font-bold transition-all duration-200 shadow-sm hover:shadow">4</button>
        <button class="number-btn bg-white hover:bg-gray-100 border border-gray-200 rounded-lg py-3 text-xl font-bold transition-all duration-200 shadow-sm hover:shadow">5</button>
        <button class="number-btn bg-white hover:bg-gray-100 border border-gray-200 rounded-lg py-3 text-xl font-bold transition-all duration-200 shadow-sm hover:shadow">6</button>
        <button class="number-btn bg-white hover:bg-gray-100 border border-gray-200 rounded-lg py-3 text-xl font-bold transition-all duration-200 shadow-sm hover:shadow">7</button>
        <button class="number-btn bg-white hover:bg-gray-100 border border-gray-200 rounded-lg py-3 text-xl font-bold transition-all duration-200 shadow-sm hover:shadow">8</button>
        <button class="number-btn bg-white hover:bg-gray-100 border border-gray-200 rounded-lg py-3 text-xl font-bold transition-all duration-200 shadow-sm hover:shadow">9</button>
        <button id="clear-btn" class="bg-gray-200 hover:bg-gray-300 border border-gray-300 rounded-lg py-3 text-xl font-bold transition-all duration-200 shadow-sm hover:shadow">
          <i class="fa fa-eraser"></i>
        </button>
      </div>
    </div>
    
    <!-- 游戏完成模态框 -->
    <div id="success-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
      <div class="bg-white rounded-xl shadow-2xl p-8 max-w-md w-full transform transition-all duration-300 scale-95 opacity-0" id="modal-content">
        <div class="text-center">
          <div class="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
            <i class="fa fa-trophy text-3xl text-secondary"></i>
          </div>
          <h2 class="text-2xl font-bold mb-2">恭喜完成!</h2>
          <p class="text-gray-600 mb-6">你成功完成了数独挑战</p>
          <div class="bg-gray-50 p-4 rounded-lg mb-6">
            <p class="text-sm text-gray-500">用时</p>
            <p id="final-time" class="text-3xl font-mono font-bold">00:00</p>
          </div>
          <button id="play-again" class="bg-primary hover:bg-primary/90 text-white px-6 py-3 rounded-lg shadow transition-all duration-200 w-full text-lg font-medium">
            再来一局
          </button>
        </div>
      </div>
    </div>
  </div>

  <script>
    // 数独游戏逻辑
    document.addEventListener('DOMContentLoaded', () => {
      // 游戏状态
      const gameState = {
        board: Array(9).fill().map(() => Array(9).fill(0)),
        solution: Array(9).fill().map(() => Array(9).fill(0)),
        selectedCell: null,
        isNoteMode: false,
        timer: null,
        startTime: 0,
        elapsedTime: 0,
        difficulty: 'medium'
      };
      
      // DOM 元素
      const sudokuBoard = document.getElementById('sudoku-board');
      const numberPad = document.getElementById('number-pad');
      const timerElement = document.getElementById('timer');
      const difficultySelect = document.getElementById('difficulty');
      const newGameButton = document.getElementById('new-game');
      const hintButton = document.getElementById('hint');
      const toggleNotesButton = document.getElementById('toggle-notes');
      const clearButton = document.getElementById('clear-btn');
      const successModal = document.getElementById('success-modal');
      const modalContent = document.getElementById('modal-content');
      const finalTimeElement = document.getElementById('final-time');
      const playAgainButton = document.getElementById('play-again');
      
      // 初始化数独板
      function initializeBoard() {
        sudokuBoard.innerHTML = '';
        
        for (let row = 0; row < 9; row++) {
          for (let col = 0; col < 9; col++) {
            const cell = document.createElement('div');
            cell.classList.add(
              'cell', 
              'flex', 
              'items-center', 
              'justify-center', 
              'cell-border',
              'aspect-square',
              'cursor-pointer',
              'transition-all',
              'duration-200'
            );
            
            // 设置厚边框以分隔3x3宫
            if ((col + 1) % 3 === 0 && col !== 8) cell.classList.add('thick-right');
            if ((row + 1) % 3 === 0 && row !== 8) cell.classList.add('thick-bottom');
            
            // 添加数据属性
            cell.dataset.row = row;
            cell.dataset.col = col;
            
            // 添加点击事件
            cell.addEventListener('click', () => selectCell(row, col));
            
            sudokuBoard.appendChild(cell);
          }
        }
      }
      
      // 选择单元格
      function selectCell(row, col) {
        // 移除之前选中单元格的高亮
        if (gameState.selectedCell) {
          const prevCell = document.querySelector(`[data-row="${gameState.selectedCell.row}"][data-col="${gameState.selectedCell.col}"]`);
          prevCell.classList.remove('bg-blue-200');
        }
        
        // 设置新的选中单元格
        gameState.selectedCell = { row, col };
        
        // 添加高亮
        const cell = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
        cell.classList.add('bg-blue-200');
        
        // 高亮相同数字
        highlightSameNumbers(gameState.board[row][col]);
      }
      
      // 高亮相同数字
      function highlightSameNumbers(number) {
        if (number === 0) return;
        
        // 移除之前的高亮
        document.querySelectorAll('.cell-highlight').forEach(cell => {
          cell.classList.remove('cell-highlight');
        });
        
        // 添加新的高亮
        document.querySelectorAll('.cell').forEach(cell => {
          const row = parseInt(cell.dataset.row);
          const col = parseInt(cell.dataset.col);
          
          if (gameState.board[row][col] === number && !(row === gameState.selectedCell.row && col === gameState.selectedCell.col)) {
            cell.classList.add('cell-highlight');
          }
        });
      }
      
      // 生成新的数独游戏
      function generateNewGame() {
        // 停止计时器
        stopTimer();
        
        // 重置游戏状态
        gameState.board = Array(9).fill().map(() => Array(9).fill(0));
        gameState.solution = Array(9).fill().map(() => Array(9).fill(0));
        gameState.selectedCell = null;
        gameState.elapsedTime = 0;
        
        // 更新计时器显示
        updateTimerDisplay();
        
        // 生成解决方案
        generateSolution();
        
        // 根据难度挖空
        removeNumbersBasedOnDifficulty();
        
        // 渲染数独板
        renderBoard();
        
        // 开始计时器
        startTimer();
      }
      
      // 生成完整的数独解决方案
      function generateSolution() {
        solveSudoku(0, 0);
      }
      
      // 递归回溯解决数独
      function solveSudoku(row, col) {
        // 如果已经填满所有行，解决方案完成
        if (row === 9) return true;
        
        // 计算下一个单元格的位置
        const nextRow = col === 8 ? row + 1 : row;
        const nextCol = col === 8 ? 0 : col + 1;
        
        // 随机尝试数字1-9
        const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
        shuffleArray(numbers);
        
        for (const num of numbers) {
          if (isValidMove(row, col, num)) {
            gameState.solution[row][col] = num;
            
            // 递归解决剩余部分
            if (solveSudoku(nextRow, nextCol)) return true;
            
            // 如果无法解决，回溯
            gameState.solution[row][col] = 0;
          }
        }
        
        return false;
      }
      
      // 检查数字是否可以放在指定位置
      function isValidMove(row, col, num) {
        // 检查行
        for (let i = 0; i < 9; i++) {
          if (gameState.solution[row][i] === num) return false;
        }
        
        // 检查列
        for (let i = 0; i < 9; i++) {
          if (gameState.solution[i][col] === num) return false;
        }
        
        // 检查3x3宫
        const startRow = Math.floor(row / 3) * 3;
        const startCol = Math.floor(col / 3) * 3;
        
        for (let i = 0; i < 3; i++) {
          for (let j = 0; j < 3; j++) {
            if (gameState.solution[startRow + i][startCol + j] === num) return false;
          }
        }
        
        return true;
      }
      
      // 根据难度挖空
      function removeNumbersBasedOnDifficulty() {
        // 复制解决方案到游戏板
        gameState.board = gameState.solution.map(row => [...row]);
        
        // 根据难度决定挖空数量
        let cellsToRemove = 30; // 默认为中等难度
        
        switch (gameState.difficulty) {
          case 'easy':
            cellsToRemove = 20;
            break;
          case 'medium':
            cellsToRemove = 30;
            break;
          case 'hard':
            cellsToRemove = 40;
            break;
          case 'expert':
            cellsToRemove = 50;
            break;
        }
        
        // 随机挖空
        let removed = 0;
        while (removed < cellsToRemove) {
          const row = Math.floor(Math.random() * 9);
          const col = Math.floor(Math.random() * 9);
          
          if (gameState.board[row][col] !== 0) {
            gameState.board[row][col] = 0;
            removed++;
          }
        }
      }
      
      // 渲染数独板
      function renderBoard() {
        // 清除所有单元格内容
        document.querySelectorAll('.cell').forEach(cell => {
          cell.innerHTML = '';
          cell.classList.remove('number-selected', 'number-candidate', 'number-conflict');
        });
        
        // 填充数字
        for (let row = 0; row < 9; row++) {
          for (let col = 0; col < 9; col++) {
            const cell = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
            const num = gameState.board[row][col];
            
            if (num !== 0) {
              // 如果是初始数字，设为灰色
              if (gameState.solution[row][col] === num && !isCellEditable(row, col)) {
                cell.innerHTML = `<span class="text-gray-700 font-bold">${num}</span>`;
                cell.classList.add('bg-gray-50');
                cell.classList.remove('cursor-pointer');
              } else {
                // 玩家填入的数字
                cell.innerHTML = `<span>${num}</span>`;
                
                // 检查是否有冲突
                if (!isValidMove(row, col, num)) {
                  cell.classList.add('number-conflict');
                } else {
                  cell.classList.add('number-candidate');
                }
              }
            }
          }
        }
      }
      
      // 检查单元格是否可编辑
      function isCellEditable(row, col) {
        return gameState.board[row][col] !== gameState.solution[row][col] || gameState.board[row][col] === 0;
      }
      
      // 处理数字输入
      function handleNumberInput(num) {
        if (!gameState.selectedCell) return;
        
        const { row, col } = gameState.selectedCell;
        
        // 如果单元格不可编辑，不做任何操作
        if (!isCellEditable(row, col)) return;
        
        if (gameState.isNoteMode) {
          // 笔记模式
          toggleNote(row, col, num);
        } else {
          // 正常模式
          gameState.board[row][col] = num;
          renderBoard();
          
          // 重新选择单元格以保持高亮
          selectCell(row, col);
          
          // 检查游戏是否完成
          checkGameCompletion();
        }
      }
      
      // 切换笔记
      function toggleNote(row, col, num) {
        const cell = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
        
        // 如果单元格有数字，不添加笔记
        if (gameState.board[row][col] !== 0) return;
        
        // 检查笔记元素
        let noteElement = cell.querySelector('.note-cell');
        
        if (!noteElement) {
          // 创建新的笔记元素
          noteElement = document.createElement('div');
          noteElement.classList.add('note-cell');
          cell.appendChild(noteElement);
          
          // 初始化所有笔记为空
          for (let i = 1; i <= 9; i++) {
            const noteValue = document.createElement('div');
            noteValue.classList.add('note-value');
            noteValue.textContent = i;
            noteElement.appendChild(noteValue);
          }
        }
        
        // 切换笔记
        const noteValues = noteElement.querySelectorAll('.note-value');
        const targetNote = noteValues[num - 1];
        
        targetNote.classList.toggle('note-value-highlight');
      }
      
      // 清除选中单元格
      function clearSelectedCell() {
        if (!gameState.selectedCell) return;
        
        const { row, col } = gameState.selectedCell;
        
        // 如果单元格不可编辑，不做任何操作
        if (!isCellEditable(row, col)) return;
        
        // 清除数字和笔记
        gameState.board[row][col] = 0;
        const cell = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
        cell.innerHTML = '';
        
        // 重新选择单元格以保持高亮
        selectCell(row, col);
      }
      
      // 检查游戏是否完成
      function checkGameCompletion() {
        // 检查所有单元格
        for (let row = 0; row < 9; row++) {
          for (let col = 0; col < 9; col++) {
            // 如果有空单元格或数字冲突，游戏未完成
            if (gameState.board[row][col] === 0 || !isValidMove(row, col, gameState.board[row][col])) {
              return false;
            }
          }
        }
        
        // 如果所有单元格都正确，游戏完成
        stopTimer();
        showSuccessModal();
        return true;
      }
      
      // 显示成功模态框
      function showSuccessModal() {
        // 设置最终时间
        finalTimeElement.textContent = timerElement.textContent;
        
        // 显示模态框
        successModal.classList.remove('hidden');
        
        // 添加动画
        setTimeout(() => {
          modalContent.classList.remove('scale-95', 'opacity-0');
          modalContent.classList.add('scale-100', 'opacity-100');
        }, 10);
      }
      
      // 隐藏成功模态框
      function hideSuccessModal() {
        modalContent.classList.remove('scale-100', 'opacity-100');
        modalContent.classList.add('scale-95', 'opacity-0');
        
        setTimeout(() => {
          successModal.classList.add('hidden');
        }, 300);
      }
      
      // 提示功能
      function provideHint() {
        if (!gameState.selectedCell) return;
        
        const { row, col } = gameState.selectedCell;
        
        // 如果单元格已经有正确数字，不提供提示
        if (gameState.board[row][col] === gameState.solution[row][col]) return;
        
        // 设置提示数字
        gameState.board[row][col] = gameState.solution[row][col];
        renderBoard();
        
        // 检查游戏是否完成
        checkGameCompletion();
      }
      
      // 开始计时器
      function startTimer() {
        gameState.startTime = Date.now() - gameState.elapsedTime;
        gameState.timer = setInterval(updateTimer, 1000);
      }
      
      // 停止计时器
      function stopTimer() {
        clearInterval(gameState.timer);
        gameState.elapsedTime = Date.now() - gameState.startTime;
      }
      
      // 更新计时器显示
      function updateTimer() {
        const elapsedTime = Date.now() - gameState.startTime;
        const minutes = Math.floor(elapsedTime / 60000);
        const seconds = Math.floor((elapsedTime % 60000) / 1000);
        
        timerElement.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
      }
      
      // 更新计时器显示（静态）
      function updateTimerDisplay() {
        const minutes = Math.floor(gameState.elapsedTime / 60000);
        const seconds = Math.floor((gameState.elapsedTime % 60000) / 1000);
        
        timerElement.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
      }
      
      // 切换笔记模式
      function toggleNotesMode() {
        gameState.isNoteMode = !gameState.isNoteMode;
        
        // 更新按钮外观
        if (gameState.isNoteMode) {
          toggleNotesButton.classList.add('bg-accent/80');
          toggleNotesButton.classList.remove('bg-accent');
        } else {
          toggleNotesButton.classList.add('bg-accent');
          toggleNotesButton.classList.remove('bg-accent/80');
        }
      }
      
      // 打乱数组顺序
      function shuffleArray(array) {
        for (let i = array.length - 1; i > 0; i--) {
          const j = Math.floor(Math.random() * (i + 1));
          [array[i], array[j]] = [array[j], array[i]];
        }
      }
      
      // 事件监听器
      function setupEventListeners() {
        // 数字按钮点击事件
        document.querySelectorAll('.number-btn').forEach(btn => {
          btn.addEventListener('click', () => {
            const num = parseInt(btn.textContent);
            handleNumberInput(num);
          });
        });
        
        // 清除按钮点击事件
        clearButton.addEventListener('click', clearSelectedCell);
        
        // 新游戏按钮点击事件
        newGameButton.addEventListener('click', generateNewGame);
        
        // 提示按钮点击事件
        hintButton.addEventListener('click', provideHint);
        
        // 切换笔记模式按钮点击事件
        toggleNotesButton.addEventListener('click', toggleNotesMode);
        
        // 难度选择事件
        difficultySelect.addEventListener('change', () => {
          gameState.difficulty = difficultySelect.value;
          generateNewGame();
        });
        
        // 再玩一次按钮点击事件
        playAgainButton.addEventListener('click', () => {
          hideSuccessModal();
          generateNewGame();
        });
        
        // 键盘输入支持
        document.addEventListener('keydown', (e) => {
          if (/^[1-9]$/.test(e.key)) {
            handleNumberInput(parseInt(e.key));
          } else if (e.key === 'Delete' || e.key === 'Backspace') {
            clearSelectedCell();
          } else if (e.key === 'n' || e.key === 'N') {
            toggleNotesMode();
          } else if (e.key === 'h' || e.key === 'H') {
            provideHint();
          } else if (e.key === 'r' || e.key === 'R') {
            generateNewGame();
          }
        });
      }
      
      // 初始化游戏
      function initGame() {
        initializeBoard();
        setupEventListeners();
        generateNewGame();
      }
      
      // 启动游戏
      initGame();
    });
  </script>
</body>
</html>    